//
//  MBDHttpClient.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/4.
//

import Foundation
import Alamofire
import SwiftyJSON

class MBDDataRequest : NSObject {
    var dataRequest : DataRequest?
    
    func httpClientResponse(completionHandler: @escaping (NSError?,MBDDataResponse?) -> Void) {
        
        let dr = self.dataRequest?.response(completionHandler: { (response : AFDataResponse<Data?>)  in
            
            switch response.result {
            case .success: do {
                let json = try JSON(data: response.data ?? Data())
                let rawDict = json.rawValue as! NSDictionary
                
                if nil == rawDict.object(forKey: "code") {
                    if let statusCode = rawDict.object(forKey: "status") {
                        let realStatusCode = (statusCode as! NSNumber).stringValue
                        if realStatusCode == "404" {
                            let er = NSError(domain: "ServiceErrorDomain", code: 4004,userInfo: [NSLocalizedDescriptionKey:"找不到服务!"])
                            completionHandler(er,nil)
                        }
                    }
                    return
                }
                
                let code = rawDict["code"]
                
                if code is String || code is NSNull {
                    
                    var codeString = ""
                    if code is String {
                        codeString = code as! String
                    } else {
                        codeString = "200"
                    }
                    
                    if codeString == "200" {
                        
                        let res = MBDDataResponse()
                        res.rawDict = rawDict as? Dictionary<String, Any>
                        completionHandler(nil,res)
                        
                    } else if codeString == "401" {

                        MBDUserCenter.shared.token = ""
                        let er = NSError(domain: "NetworkErrorDomain", code: 10000,userInfo: [NSLocalizedDescriptionKey:"请重新登录"])
                        completionHandler(er,nil)
                        
                    } else if codeString == "500" {

                        let msg : String = rawDict["msg"] is String ? rawDict["msg"] as! String : (rawDict["msg"] as! String)
                        let er = NSError(domain: "NetworkErrorDomain", code: 20000,userInfo: [NSLocalizedDescriptionKey:msg])
                        
                        completionHandler(er,nil)
                    } else {
                        completionHandler(nil,MBDDataResponse())
                    }
                    
                } else {
                    let msg : String = "服务器异常，请联系管理员"
                    let er = NSError(domain: "HostErrorDomain", code: 30000,userInfo: [NSLocalizedDescriptionKey:msg])
                    completionHandler(er,nil)
                }
                

           } catch {

           }
                break
                
            case let .failure(error):
                if let underlyingError = error.underlyingError {
                    if let urlError = underlyingError as? URLError {
                        switch urlError.code {
                        case .timedOut:
                            let er = NSError(domain: "NetworkErrorDomain", code: 10001,userInfo: [NSLocalizedDescriptionKey:"网络异常，请稍后再试"])
                            completionHandler(er,nil)

                        case .notConnectedToInternet:
                            print("Not connected")

                        default:
                            print("Not connected")
                        }

                    }
                }
                
            }
        })
        self.dataRequest = dr
    }
    
}

class MBDHttpClient : NSObject {
    static let shared = MBDHttpClient()

    open func request(_ path: String, method: HTTPMethod = .get,
                      parameters: Parameters? = nil,encoding: ParameterEncoding = JSONEncoding.default,
                      headers: HTTPHeaders? = nil) -> MBDDataRequest {
        
        var paraHeaders : HTTPHeaders
        if nil == headers {
            paraHeaders = ["Content-Type":"application/json","Authorization":"Bearer ".appending(MBDUserCenter.shared.token)]
        } else {
            paraHeaders = headers!
        }

        let url = MBDHostManager.shared.host + path
        let request = AF.request(url,method: method,parameters: parameters,encoding: encoding,headers: paraHeaders,requestModifier: {$0.timeoutInterval = 5})
        
        let rqst = MBDDataRequest()
        rqst.dataRequest = request
        return rqst
    }
    
    open func doGetRequest(_ path: String, method: HTTPMethod = .get,
                      parameters: Parameters? = nil,encoding: ParameterEncoding = URLEncoding.default,
                      headers: HTTPHeaders? = nil) -> MBDDataRequest {
        
        let headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded","Authorization":"Bearer ".appending(MBDUserCenter.shared.token)]

        let url = MBDHostManager.shared.host + path
        let request = AF.request(url,method: method,parameters: parameters,encoding: encoding,headers: headers,requestModifier: {$0.timeoutInterval = 5})
        
        let rqst = MBDDataRequest()
        rqst.dataRequest = request
        return rqst
        
    }
    
    open func doPostRequest(_ path: String,
                      parameters: Parameters? = nil,
                      headers: HTTPHeaders? = nil) -> MBDDataRequest {
        
        let headers : HTTPHeaders = ["Content-Type":"application/json","Authorization":"Bearer ".appending(MBDUserCenter.shared.token)]

        let url = MBDHostManager.shared.host + path
        let request = AF.request(url,method: .post,parameters: parameters,encoding: JSONEncoding.default,headers: headers,requestModifier: {$0.timeoutInterval = 5})
        
        let rqst = MBDDataRequest()
        rqst.dataRequest = request
        return rqst
    }
    
    open func doUploadFileRequest(_ path: String,
                                  data : Data,
                                  fileName: String,
                      parameters: Parameters? = nil,
                      headers: HTTPHeaders? = nil) -> MBDDataRequest {
        
        let headers : HTTPHeaders = ["Authorization":"Bearer ".appending(MBDUserCenter.shared.token),"Content-Type":"multipart/form-data"]

        let url = MBDHostManager.shared.host + path
        
        let uploadRequest = AF.upload(multipartFormData: { multipartFormData in
//            multipartFormData.append(data, withName: "file")
            multipartFormData.append(data, withName: "file", fileName: "file.jpg",mimeType: "image/jpg")
          }, to: url,headers: headers)
                
        let rqst = MBDDataRequest()
        rqst.dataRequest = uploadRequest
        return rqst
    }
    
}


enum MBDHttpClientError : Error,LocalizedError {
    case msg(String)
    
    var errorDescription: String? {
        switch self {
        case let .msg(msg):
            return msg
        }
    }
}
